<template>
  <a-drawer
    :title="title"
    width="90%"
    :visible="visible"
    @close="
      () => {
        this.visible = false
      }
    "
  >
    <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
      <a-row>
        <a-col :span="8">
          <!-- <a-form-model-item label="审批状态" prop="ApprovalStatus">
            <a-input v-model="entity.ApprovalStatus" autocomplete="off" placeholder="审批状态" />
          </a-form-model-item> -->
          <a-form-model-item label="客户名称" prop="Object">
            <Myuser disabled v-model="entity.Object" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="销售经理" prop="AccountManager">
            <a-input disabled v-model="entity.AccountManager" autocomplete="off" placeholder="销售经理" />
          </a-form-model-item>
          <!-- <a-form-model-item label="客户ID" prop="CustomerId">
          <a-input v-model="entity.CustomerId" autocomplete="off" placeholder="客户ID" />
        </a-form-model-item> -->
        </a-col>

        <a-col :span="8">
          <a-form-model-item label="单据号" prop="DocumentNo">
            <a-input disabled v-model="entity.DocumentNo" autocomplete="off" placeholder="单据号" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="核算结束时间" prop="AccountingEndDate">
            <a-date-picker format="YYYY-MM-DD" style="width: 100%" v-model="entity.AccountingEndDate" />
            <!-- <a-input v-model="entity.AccountingEndDate" autocomplete="off" placeholder="核算结束时间" /> -->
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="经办人" prop="Transactor">
            <a-input v-model="entity.Transactor" autocomplete="off" placeholder="经办人" />
          </a-form-model-item>
        </a-col>

        <a-col :span="8">
          <a-form-model-item label="组织机构" prop="Department">
            <a-input v-model="entity.Department" autocomplete="off" placeholder="组织机构" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="返料规则" prop="Object">
            <a-input style="width: 100%" disabled v-model="entity.RuleMainName" placeholder="返料规则"></a-input>
          </a-form-model-item>
        </a-col>

        <a-col :span="8">
          <a-form-model-item label="备注" prop="Remark">
            <a-input v-model="entity.Remark" autocomplete="off" placeholder="备注" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="申请时间" prop="ApplyDate">
            <a-date-picker format="YYYY-MM-DD" style="width: 100%" v-model="entity.ApplyDate" />
            <!-- <a-input v-model="entity.AccountingEndDate" autocomplete="off" placeholder="核算结束时间" /> -->
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item v-if="title == '查看' || title == '审核' || title == '修改'" label="审核日期">
            <a-date-picker
              :disabled="title == '查看'"
              format="YYYY-MM-DD"
              style="width: 100%"
              v-model="entity.ApprovalDate"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            v-if="title == '查看' || title == '审核' || title == '修改'"
            label="审批意见"
            prop="ApprovalComments"
          >
            <a-input :disabled="title == '查看'" v-model="entity.ApprovalComments" autocomplete="off" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-button type="primary" class="addTable" v-if="title == '新建返料申请'" @click="addTable">计算</a-button>
        </a-col>
      </a-row>
    </a-form-model>
    <PriceChoose ref="materialChoose" @onChoose="handleChoose"></PriceChoose>
    <a-table
      ref="table"
      :scroll="{ y: 530 }"
      :columns="columns"
      :rowKey="(row, index) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys }"
      :bordered="true"
      size="small"
    >
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
      <template slot="ProductName" slot-scope="text, record">
        <span>{{ record.ProductId }}/{{ text }}</span>
      </template>
      <template slot="AuxiliaryQuantity" slot-scope="text, record">
        <a-input
          size="small"
          class="input"
          type="number"
          v-model="record.AuxiliaryQuantity"
          style="text-align: right"
        ></a-input>
      </template>
      <!-- 批次 -->
      <template slot="Batch" slot-scope="text, record">
        <a-input size="small" class="input" type="number" v-model="record.Batch" style="text-align: right"></a-input>
      </template>
      <!-- 备注 -->
      <template slot="Remark" slot-scope="text, record">
        <a-input size="small" class="input" v-model="record.Remark"></a-input>
      </template>
      <span slot="action" slot-scope="text, record">
        <template>
          <a v-if="hasPerm('GMM_GiftMaterialApplyDetails.Edit')" @click="handleEdit(record.Id)">编辑</a>
          <a-divider
            v-if="hasPerm('GMM_GiftMaterialApplyDetails.Edit') && hasPerm('GMM_GiftMaterialApplyDetails.Delete')"
            type="vertical"
          />
          <a @click="handleDelete([record.Id])">删除</a>
        </template>
      </span>
    </a-table>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '5px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1
      }"
    >
      <a-button type="primary" @click="addTable">添加</a-button>&nbsp; <a-button @click="close">取消</a-button>&nbsp;
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
const columns = [
  // { title: '更新时间', dataIndex: 'UpdateTime', width: '10%' },
  { title: '品名', dataIndex: 'ProductName', scopedSlots: { customRender: 'ProductName' } },
  // { title: '产品ID', dataIndex: 'ProductId' },
  { title: '规格型号', dataIndex: 'cInvStd' },
  // { title: '产品ID', dataIndex: 'ProductId' },
  {
    title: '数量',
    dataIndex: 'AuxiliaryQuantity',
    align: 'center',
    scopedSlots: { customRender: 'AuxiliaryQuantity' }
  },
  // { title: '批次', dataIndex: 'Batch', align: 'right', scopedSlots: { customRender: 'Batch' } },
  { title: '备注', dataIndex: 'Remark', scopedSlots: { customRender: 'Remark' } },
  //{ title: '创建时间', dataIndex: 'CreateTime', width: '10%', scopedSlots: { customRender: 'CreateTime' } },
  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' } }
]

import OperatorCache from '@/utils/cache/OperatorCache'
import Myuser from '@/components/MyuserCloose/List.vue'
import PriceChoose from '@/components/PriceChoose/MaterialApply.vue'
import moment from 'moment'
export default {
  props: {
    parentObj: Object
  },

  data() {
    return {
      columns,
      data: [],
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      cc: false,
      filters: {},
      sorter: { field: 'Id', order: 'desc' },
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      selectedRowKeys: [],
      visible: false,
      loading: false,
      entity: {},
      rules: {},
      title: '',
      Id: ''
    }
  },
  components: {
    Myuser,
    PriceChoose
  },
  watch: {
    data: {
      handler(n, o) {
        //console.log(n)
        n.forEach(item => {
          if (Number(item.AuxiliaryQuantity) < 0) {
            this.$set(item, 'AuxiliaryQuantity', 1)
            this.$message.warning('数量不能小于0')
            return
          }
        })
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    handleChoose(a) {
      //console.log(123)
      //console.log(a)

      var ar = []

      this.data.forEach(item => {
        //console.log(this.data)
        a.forEach((val, i) => {
          //console.log(val)
          if (item.ProductId == val.cInvCode) {
            ar.push(val)
            delete a[i]
          }
        })
      })
      //console.log(ar)

      if (ar.length == 0) {
        a.forEach(item => {
          //console.log(this.data)

          this.data.push({
            ProductId: item.cInvCode,
            ProductName: item.cInvName,
            cInvCode: item.cInvCode,
            cInvStd: item.cInvStd
          })
        })
        //console.log(ar)
        // this.data = [...this.data, ...a]
      } else {
        this.$message.error('重复产品已筛选掉')
        a.forEach(item => {
          //console.log(item)
          this.data = [...this.data, item]
        })

        //console.log(a)
      }
    },
    //销售经理
    op() {
      return OperatorCache.info
    },
    close() {
      this.visible = false

      this.entity = {}
    },

    addTable() {
      // //console.log(this.entity.Object.cCusCode);

      if (this.entity.Object) {
        //console.log(this.entity)
        if (this.entity.Obe) {
          this.$refs.materialChoose.openChoose(this.entity.Obe)
        } else {
          this.$refs.materialChoose.openChoose(this.entity.Object.cCusCode)
        }

        //console.log(12113, '#####')
      } else {
        //console.log(12113, '999999')
        this.$message.error('请先选择客户')
        return
      }
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      // this.getDataList()
    },
    init() {
      this.visible = true

      this.entity = {}
      this.data = []

      this.entity.ApplyDate = moment(new Date())

      //console.log(this.$children)
      // this.entity.LinkMan = this.op().RealName
      // this.entity.AccountManager = this.op().RealName
    },

    openForm(item, title) {
      this.init()
      this.title = title
      if (item.cCusName) this.$set(this.entity, 'Object', item.cCusName)
      if (item.cCusCode) this.$set(this.entity, 'Obe', item.cCusCode)

      this.$set(this.entity, 'AccountManager', item.AllocationName)
      this.cCusName = item.cCusName
    },
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        this.loading = true

        if (this.title == '客户返料' && this.entity.Object) {
          //console.log(this.entity.Object)
          this.entity.CustomerName = this.entity.Object
          this.entity.CustomerId = this.entity.Obe
          //console.log(this.entity.CustomerName)
        }
        // if (this.title == '编辑返料申请' && this.cc) {
        //   //console.log(this.entity)
        //   //console.log(this.cc)
        //   this.entity.CustomerName = this.entity.Object.cCusName || this.entity.Object
        //   this.entity.CustomerId = this.entity.Object.cCusCode || this.entity.Obe
        //   // this.entity.CustomerName = this.entity.Object
        //   // this.entity.CustomerId = this.entity.Obe
        // }
        // if (this.title == '编辑返料申请' && !this.cc) {
        //   //console.log(this.cc)
        //   //console.log(this.entity)
        //   this.entity.CustomerName = this.entity.Object
        //   this.entity.CustomerId = this.entity.Obe
        // }
        var entityData = this.entity
        var GMM_GiftMaterialApplyDetailsList = [...this.data]

        entityData.GMM_GiftMaterialApplyDetailsList = GMM_GiftMaterialApplyDetailsList
        //console.log(entityData)

        this.$http.post('/GiftManagement/GMM_GiftMaterialApplyMain/SaveData', entityData).then(resJson => {
          this.loading = false

          if (resJson.Success) {
            this.$message.success('操作成功!')
            this.visible = false

            this.parentObj.getDataList()
          } else {
            this.$message.error(resJson.Msg)
          }
        })
      })
    }
  }
}
</script>
